<template>
  <div class="search-box">
    <el-form ref="formRef" :inline="true" :model="searchFrom" class="demo-form-inline" label-suffix=":">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="searchFrom.projectName" placeholder="项目名称" style="width: 250px" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目编号" prop="projectNum">
            <el-input v-model="searchFrom.projectNum" placeholder="项目编号" style="width: 250px" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目类型" prop="projectType">
            <el-select v-model="searchFrom.projectType" placeholder="项目类型" clearable style="width: 250px">
              <el-option label="类型A" value="A" />
              <el-option label="类型B" value="B" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="其他数据" prop="count">
            <el-select-v2 v-model="searchFrom.count" placeholder="其他" :options="options" clearable filterable
              style="width: 250px" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目时间" prop="timeRange">
            <el-date-picker v-model="searchFrom.timeRange" type="daterange" range-separator="~" start-placeholder="开始日期"
              end-placeholder="结束日期" unlink-panels value-format="YYYY-MM-DD" :disabled-date="disabledDate"
              style="width: 230px" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="选择月份" prop="monthRange">
            <el-date-picker v-model="searchFrom.monthRange" type="monthrange" range-separator="~" start-placeholder="开始月份"
              end-placeholder="结束月份" unlink-panels value-format="YYYY-MM" :disabled-date="disabledDate"
              :shortcuts="shortcuts" style="width: 230px" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" justify="center">
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <hr />
  <div class="operate-box">
    <el-row justify="end">
      <el-button link type="primary" @click="setHeader">设置表头</el-button>
    </el-row>
  </div>
  <hr />
  <div class="table-box" style="height: 550px">
    <el-auto-resizer>
      <template #default="{ height, width }">
        <el-table-v2 :columns="columns" :data="tableData" :width="width" :height="height" fixed />
      </template>
    </el-auto-resizer>
    <el-row justify="end">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 40]" background layout="total, prev, pager, next, sizes" :total="pagination.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-row>
  </div>
  <HeaderDialog ref="headerDialog" v-model:columns="columns" />
</template>

<script setup lang="ts">
import { computed, reactive, ref, watchEffect } from "vue";
import { FormInstance, dayjs } from "element-plus";
import HeaderDialog from "./components/headerDialog.vue";
import userStore from "@/store";
import { storeToRefs } from "pinia";

const { projectStore } = userStore();
const { myColumns } = storeToRefs(projectStore);

const headerDialog = ref();

const formRef = ref<FormInstance>();
const searchFrom = reactive({
  projectName: "",
  projectNum: "",
  projectType: "",
  count: null,
  timeRange: "",
  monthRange: "",
});
const options = Array.from({ length: 10000 }).map((_, index) => ({
  label: `${index + 1}`,
  value: `${index + 1}`,
}));

const disabledDate = (date: any) => {
  return dayjs(date).startOf("day") >= dayjs(new Date()).startOf("day");
};

const shortcuts = [
  {
    text: "This month",
    value: [new Date(), new Date()],
  },
  {
    text: "This year",
    value: () => {
      const end = new Date();
      const start = new Date(new Date().getFullYear(), 0);
      return [start, end];
    },
  },
  {
    text: "Last 6 months",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 6);
      return [start, end];
    },
  },
];

const onSubmit = () => {
  console.log("submit!", searchFrom);
};
const resetForm = () => {
  formRef.value?.resetFields();
};

const generateColumns = (length = 10, prefix = "column-", props?: any) =>
  Array.from({ length }).map((_, columnIndex) => ({
    ...props,
    key: `${prefix}${columnIndex}`,
    dataKey: `${prefix}${columnIndex}`,
    title: `Column ${columnIndex}`,
    width: 150,
  }));

const generateData = (
  columns: ReturnType<typeof generateColumns>,
  length = 200,
  prefix = "row-"
) =>
  Array.from({ length }).map((_, rowIndex) => {
    return columns.reduce(
      (rowData, column, columnIndex) => {
        rowData[column.dataKey] = `Row ${rowIndex} - Col ${columnIndex}`;
        return rowData;
      },
      {
        id: `${prefix}${rowIndex}`,
        parentId: null,
      }
    );
  });
const columns = ref(
  myColumns.value.length ? myColumns.value : generateColumns(10)
);
const data = generateData(columns.value, 1000);
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: data.length,
});
//前端限制分页（tableData为当前展示页表格）
const tableData = computed(() => {
  return data.filter(
    (item, index) =>
      index < pagination.currentPage * pagination.pageSize &&
      index >= pagination.pageSize * (pagination.currentPage - 1)
  );
});
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pagination.pageSize = val;
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  pagination.currentPage = val;
};

// 设置表头
const setHeader = () => {
  headerDialog.value.show();
};
watchEffect(() => {
  projectStore.set_columns(columns.value);
});
</script>

<style scoped></style>
